/**
 * 下载器
 */
class ScriptInstaller {
  constructor() {
    this.fileManager = FileManager.iCloud()
    this.documentsDirectory = this.fileManager.documentsDirectory()
  }

  async installScript(name, sourceUrl, icon, color) {
    let filePath = this.fileManager.joinPath(this.documentsDirectory, name + '.js');
    let req = new Request(sourceUrl);
    let code = await req.loadString();
    let codeToStore = Data.fromString(`// Variables used by Scriptable.\n// These must be at the very top of the file. Do not edit.\n// icon-color: ${color}; icon-glyph: ${icon};\n${code}`);
    this.fileManager.write(filePath, codeToStore);
  }
}

// 弹窗下载
const urlInputAlert = new Alert()
urlInputAlert.title = '下载器'
urlInputAlert.addAction("取消")
urlInputAlert.addAction("确定")
urlInputAlert.addTextField("请输入脚本下载地址")
let selectIndex = await urlInputAlert.presentAlert()
if (selectIndex == 1) { // 确定下载
  const jsUrl = urlInputAlert.textFieldValue()
  if (jsUrl.length == 0) return
  // 脚本安装名字
  const nameInputAlert = new Alert()
  urlInputAlert.title = '下载器'
  nameInputAlert.addAction("确定")
  nameInputAlert.addTextField("请输入脚本名字")
  selectIndex = await nameInputAlert.presentAlert()
  // 脚本名字
  const jsName = nameInputAlert.textFieldValue()
  if(jsName.length == 0) return
  // 进行下载安装
  await new ScriptInstaller().installScript(jsName, jsUrl, 'user-astronaut', 'red');
}